<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片轮播</title>
    <style>
        .he {
            width: 400px;
            margin: 10% auto;
            position: relative;
        }
        img {
            width: 400px;
            display: block;
        }
        .b {
            position: absolute;
            bottom: 10px;
            left: 50%;
            transform: translateX(-50%);
        }
        button.active {
            background: yellow;
        }
    </style>
</head>
<body>
<div class="he">
    <img src="./image/1.jpg" class="im">
    <div class="b">
        <button class="active"></button>
        <button ></button>
        <button ></button>
    </div>
</div>

<script>
    const arr = [
        './image/1.jpg',
        './image/2.jpg',
        './image/3.jpg'
    ];

    let a = 0;
    let intervalId = null;

    const im = document.querySelector(".im");
    const div = document.querySelector("div");
    const buttons = document.querySelectorAll(".b button");



    // 鼠标悬停开始轮播
    div.addEventListener("mouseenter", () => {
        if (!intervalId) {
            intervalId = setInterval(() => {
                a = (a + 1) % arr.length;
                updateImage(a);
            }, 1000);
        }
    });

    // 鼠标离开停止轮播
    div.addEventListener("mouseleave", () => {
        clearInterval(intervalId);
        intervalId = null;
    });


    function updateImage(index) {
        a = index;
        im.src = arr[a];
        buttons.forEach((btn, i) => {
            btn.classList.toggle("active", i === a);
        });
    }
    // 点击按钮切换图片
    buttons.forEach((btn, i) => {
        btn.addEventListener("click", () => {
            updateImage(i);
        });
    });
</script>
</body>
</html>
